package cn.edu.nwafu.core.listener;

import cn.edu.nwafu.core.mapper.AircraftInfoMapper;
import cn.edu.nwafu.core.pojo.entity.AircraftInfo;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;

import java.util.ArrayList;
import java.util.List;

public class ExcelAircraftInfoListener extends AnalysisEventListener<AircraftInfo> {

    private AircraftInfoMapper aircraftInfoMapper;

    // 数据列表
    private List<AircraftInfo> list = new ArrayList<>();
    // 每隔五条记录批量存储一次数据
    private static final int BATCH_COUNT = 5;

    public ExcelAircraftInfoListener(AircraftInfoMapper aircraftInfoMapper) {
        this.aircraftInfoMapper = aircraftInfoMapper;
    }

    @Override
    public void invoke(AircraftInfo data, AnalysisContext context) {
        list.add(data);
        if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
    }

    private void saveData() {
        aircraftInfoMapper.insertBatch(list);
    }
}
